package com.github.thinwonton.cas.showcase.webapp.cms.web.filter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.jasig.cas.client.session.SingleSignOutHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 拦截CAS发过来的退出登录报文
 */
public class CasLogoutFilter extends AdviceFilter {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    private static final SingleSignOutHandler handler = new SingleSignOutHandler();


    public void setLogoutParameterName(final String name) {
        handler.setLogoutParameterName(name);
    }


    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {

        final HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        if (handler.isLogoutRequest(httpServletRequest)) {
            //CAS退出登录报文，清理现场
            if (logger.isTraceEnabled()) {
                logger.trace("received cas logout request, start cleaning.");
            }

            handler.destroySession(httpServletRequest);

            try {
                Subject subject = SecurityUtils.getSubject();
                subject.logout();
            } catch (SessionException ise) {
                logger.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
            }

            if (logger.isTraceEnabled()) {
                logger.trace("received cas logout request, clean end.");
            }

            return false;
        }

        return true;
    }

}
